package com.lepu.app.fun.bbs;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.app.application.MyApplication;
import com.app.utils.LoginUtil;
import com.app.utils.MyNetUtil;
import com.app.utils.SdLocal;
import com.app.utils.Setting;
import com.app.utils.UmengEvent;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.EmojiFilter;
import com.core.lib.utils.PopUtil;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.utils.photo.UniversalImageLoadTool;
import com.core.lib.widget.CircularImageView;
import com.core.lib.widget.GoogleRefreshLayout;
import com.lepu.app.fun.bbs.adapter.AdapterBbsDetail;
import com.lepu.app.fun.bbs.bean.BeanBbs;
import com.lepu.app.fun.bbs.bean.BeanBbsDetail;
import com.lepu.app.fun.my.MyArticleInfoActivity;
import com.lepu.app.fun.my.MyReportActivity;
import com.lepu.app.fun.my.MyTieZiActivity;
import com.lepu.app.fun.my.bean.BeanMyArticle;
import com.lepu.app.main.activity.AppImageBroswerActivity;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.core.lib.widget.GoogleRefreshLayout.OnLoadListener;
import com.lepu.pasm.R;

import lib.share.utils.CallBack;
import lib.share.utils.ShareLib;

public class BbsDetailActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, AsyncRequest, OnRefreshListener, OnLoadListener {
	private static final String REQUEST_DATA = "request_data";
	private static final String REQUEST_DATA_MORE = "request_data_more";
	private static final String REQUEST_FAVOR = "request_favor";
	private static final String REQUEST_FAVOR_CANNEL = "request_favor_cannel";
	private static final String REQUEST_REPLY = "request_reply";

	private static final int MSG_DATA_SUCCESS = 10;
	private static final int MSG_DATA_FAIL = 11;
	private static final int MSG_DATA_MORE_SUCCESS = 12;
	private static final int MSG_DATA_MORE_FAIL = 13;
	
	private static final int MSG_FAVOR_SUCESS = 21;
	private static final int MSG_FAVOR_FAIL = 22;
	private static final int MSG_FAVOR_EXIT_SUCESS = 23;
	private static final int MSG_FAVOR_EXIT_FAIL = 24;
	private static final int MSG_COLLECT_SUCESS = 25;
	private static final int MSG_COLLECT_FAIL = 26;
	private static final int MSG_COLLECT_CANNEL_SUCESS = 27;
	private static final int MSG_COLLECT_CANNEL_FAIL = 28;
	private static final int MSG_REPLY_SUCESS = 29;
	private static final int MSG_REPLY_FAIL = 30;
	
	private GoogleRefreshLayout mGoogleRefreshLayout = null;
	private ListView mDataListView = null;
	private View mHeadView = null;
	private AdapterBbsDetail mDataAdapter = null;
	private ArrayList<BeanBbsDetail> mDataArrayList;
	private int mCurrentPage = 1;
	private int mMaxId = -1;
	
	private TextView favorTextView;
	private TextView collectTextView;
	private ImageView mCollectImage;
	private ImageView mFavorImage;
	private ImageView mCommentImage;
	private ImageView mMoreImage;
	private ImageView mShareImage; //分享
	
	private String mThreadId;  //列表bean
	private BeanBbsDetail mBeanBbsDetail;  //head bean
	
	public static BbsDetailActivity mInstance;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bbs_detail_activity);
		mInstance = this;
		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mInstance = null;
	}

	public static BbsDetailActivity getInstance(){
		return mInstance;
	}
	
	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}
	
	private void showHideNoDataLayout(boolean isShow)
	{
		LinearLayout noDataLayout = (LinearLayout)findViewById(R.id.noDataLayout);
		if(noDataLayout != null)
		{
			if(isShow)
			{
				noDataLayout.setVisibility(View.VISIBLE);
			}else{
				noDataLayout.setVisibility(View.GONE);
			}
		}
	}
	
	private void showFirstLoadDataLayout(boolean isShow)
	{
		LinearLayout firstLoadDataLayout = (LinearLayout) findViewById(R.id.firstLoadDataLayout);
		if(firstLoadDataLayout != null)
		{
			if(isShow)
			{
				if(mDataArrayList == null || mDataArrayList.size() == 0)
				{
					firstLoadDataLayout.setVisibility(View.VISIBLE);
				}
				
				LinearLayout noDataLayout = (LinearLayout) findViewById(R.id.noDataLayout);
				noDataLayout.setVisibility(View.GONE);
				
			}else{
				firstLoadDataLayout.setVisibility(View.GONE);
			}
		}
	}

	/**
	 * 初始化方法
	 */
	@SuppressWarnings("deprecation")
	@SuppressLint({ "ResourceAsColor", "InflateParams" })
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("");
		topbar.setonTopbarNewLeftLayoutListener(this);
		
		Intent intent = this.getIntent();
		mThreadId = intent.getStringExtra("threadId");
		
  		//Listview
  		mDataListView = (ListView) findViewById(R.id.dataListView);
		mGoogleRefreshLayout = (GoogleRefreshLayout) findViewById(R.id.swipeLayout);
		mGoogleRefreshLayout.setOnRefreshListener(this);
		mGoogleRefreshLayout.setOnLoadListener(this);
		mGoogleRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
				R.color.color_listview_refresh_2,
				R.color.color_listview_refresh_3,
				R.color.color_listview_refresh_4);

		mDataListView.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == 0) {
					UniversalImageLoadTool.resume();
				} else {
					UniversalImageLoadTool.pause();
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
								 int visibleItemCount, int totalItemCount) {
			}
		});
		
		UniversalImageLoadTool.clear();
		mDataArrayList = new ArrayList<BeanBbsDetail>();
		
		mCollectImage = (ImageView) findViewById(R.id.bbs_detail_collect_image);
		mFavorImage = (ImageView) findViewById(R.id.bbs_detail_favor_image);
		mCommentImage = (ImageView) findViewById(R.id.bbs_detail_comment_image);
		mShareImage = (ImageView) findViewById(R.id.bbs_detail_share_image);
		mMoreImage = (ImageView) findViewById(R.id.bbs_detail_more_image);
		
		mCollectImage.setOnClickListener(new ViewOnclickListener());
		mFavorImage.setOnClickListener(new ViewOnclickListener());
		mCommentImage.setOnClickListener(new ViewOnclickListener());
		mShareImage.setOnClickListener(new ViewOnclickListener());
		mMoreImage.setOnClickListener(new ViewOnclickListener());

		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				mGoogleRefreshLayout.setRefreshing(true);  //直接调用是没有用的
			}
		}, 100);
		request(false);
	}
	
	@SuppressLint({ "InflateParams", "SimpleDateFormat" })
	private void setInitView(final BeanBbsDetail beanBbsdetail){
		if(mHeadView != null){
			mDataListView.removeHeaderView(mHeadView);
		}
		
		mHeadView = LayoutInflater.from(BbsDetailActivity.this).inflate(R.layout.bbs_detail_head_view, null);
		
		CircularImageView iconImageView = (CircularImageView) mHeadView.findViewById(R.id.iconImageView);
		TextView nameTextView = (TextView) mHeadView.findViewById(R.id.bbs_detail_name);
		TextView typeTextView = (TextView) mHeadView.findViewById(R.id.bbs_detail_type);
		ImageView topImageView = (ImageView) mHeadView.findViewById(R.id.bbs_detail_top_icon);
		ImageView goodImageView = (ImageView) mHeadView.findViewById(R.id.bbs_detail_good_icon);
		TextView titleTextView = (TextView) mHeadView.findViewById(R.id.bbs_detail_title);
		TextView timeTextView = (TextView) mHeadView.findViewById(R.id.bbs_detail_time);
		TextView lookTextView = (TextView) mHeadView.findViewById(R.id.bbs_detail_look);
		favorTextView = (TextView) mHeadView.findViewById(R.id.bbs_detail_favor);
		collectTextView = (TextView) mHeadView.findViewById(R.id.bbs_detail_collect);
		TextView contentTextView = (TextView) mHeadView.findViewById(R.id.bbs_detail_content);
		TextView commentTextView = (TextView) mHeadView.findViewById(R.id.bbs_detail_comment_count);
		ImageView commentImage11 = (ImageView) mHeadView.findViewById(R.id.comment_image_11);
		ImageView commentImage21 = (ImageView) mHeadView.findViewById(R.id.comment_image_21);
		ImageView commentImage22 = (ImageView) mHeadView.findViewById(R.id.comment_image_22);
		ImageView commentImage31 = (ImageView) mHeadView.findViewById(R.id.comment_image_31);
		ImageView commentImage32 = (ImageView) mHeadView.findViewById(R.id.comment_image_32);
		ImageView commentImage33 = (ImageView) mHeadView.findViewById(R.id.comment_image_33);
		LinearLayout commentImageLayout = (LinearLayout) mHeadView.findViewById(R.id.comment_image_layout);
		LinearLayout commentImageLayout1 = (LinearLayout) mHeadView.findViewById(R.id.comment_image_layout1);
		LinearLayout commentImageLayout2 = (LinearLayout) mHeadView.findViewById(R.id.comment_image_layout2);
		LinearLayout commentImageLayout3 = (LinearLayout) mHeadView.findViewById(R.id.comment_image_layout3);
		
		// 头像
		LoginUtil.loadSelfUserImage(BbsDetailActivity.this,iconImageView,beanBbsdetail.AuthorID);
		nameTextView.setText(beanBbsdetail.NickName);
		typeTextView.setText(beanBbsdetail.NickName);
		//time
		long timeLong = Long.valueOf(beanBbsdetail.RecordCreateTime)*1000;
		SimpleDateFormat sdf=new SimpleDateFormat(DateUtilBase.DATE_ALL_ALL);  
		String timeString = sdf.format(new Date(timeLong)); 
		timeTextView.setText(DateUtilBase.friendly_time(timeString));
		
		lookTextView.setText("· 阅读 "+beanBbsdetail.ViewCount);
		favorTextView.setText("· 点赞 "+beanBbsdetail.FavourCount);
		collectTextView.setText("· 收藏 "+beanBbsdetail.CollectCount);
		contentTextView.setText(beanBbsdetail.Content);
		commentTextView.setText(String.valueOf(beanBbsdetail.ReplyCount));
		
		iconImageView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				LoginUtil.jumpUserInfo(BbsDetailActivity.this,beanBbsdetail.AuthorID);
			}
		});
		
		//置顶 or 精华
		if(beanBbsdetail.IsTop == 1){
			topImageView.setVisibility(View.VISIBLE);
			if(beanBbsdetail.IsGood == 1){
				goodImageView.setVisibility(View.VISIBLE);
	        	titleTextView.setText("                 "+beanBbsdetail.Subject);
			}else{
				titleTextView.setText("           "+beanBbsdetail.Subject);
			}
		}else{
	        if(beanBbsdetail.IsGood == 1){
	        	goodImageView.setVisibility(View.VISIBLE);
	        	titleTextView.setText("      "+beanBbsdetail.Subject);
			}else{
				goodImageView.setVisibility(View.GONE);
				titleTextView.setText(beanBbsdetail.Subject);
			}
		}
		
	   
        
        typeTextView.setSelected(true);
        //类型
    	if(Integer.valueOf(beanBbsdetail.ForumID) == 1)
		{
    		typeTextView.setText(getResources().getString(R.string.bbs_type1));
    		typeTextView.setTextColor(getResources().getColor(R.color.color_my_medicion));
    		typeTextView.setBackgroundResource(R.drawable.app_text_selector2);
		}else if(Integer.valueOf(beanBbsdetail.ForumID) == 2){
			typeTextView.setText(getResources().getString(R.string.bbs_type2));
			typeTextView.setTextColor(getResources().getColor(R.color.color_my_food));
			typeTextView.setBackgroundResource(R.drawable.app_text_selector3);
		}
        
        List<String> imageList = BeanBbsDetail.parseJsonImage(beanBbsdetail.PicUrls);
        
        //图片
  		if(imageList !=null && imageList.size() > 0){
  			boolean hasDate = false;
			for(int i=0 ; i<imageList.size(); i++){
				if(!TextUtils.isEmpty(imageList.get(i))){
					hasDate = true;
				}
			}
			
			if(hasDate){
				commentImageLayout.setVisibility(View.VISIBLE);
			}else{
				commentImageLayout.setVisibility(View.GONE);
			}
  			
  			if(imageList.size() == 1){
  				commentImageLayout1.setVisibility(View.VISIBLE);
  				commentImageLayout2.setVisibility(View.GONE);
  				commentImageLayout3.setVisibility(View.GONE);
  				UniversalImageLoadTool.disPlay(imageList.get(0), commentImage11, R.drawable.app_icon_load_image);
  				commentImage11.setOnClickListener(imageClickListener((String[])imageList.toArray(new String[imageList.size()]), 1));
  			}else if(imageList.size() == 2){
  				commentImageLayout2.setVisibility(View.VISIBLE);
  				commentImageLayout1.setVisibility(View.GONE);
  				commentImageLayout3.setVisibility(View.GONE);
  				UniversalImageLoadTool.disPlay(imageList.get(0), commentImage21, R.drawable.app_icon_load_image);
  				UniversalImageLoadTool.disPlay(imageList.get(1), commentImage22, R.drawable.app_icon_load_image);
  				commentImage21.setOnClickListener(imageClickListener((String[])imageList.toArray(new String[imageList.size()]), 1));
  				commentImage22.setOnClickListener(imageClickListener((String[])imageList.toArray(new String[imageList.size()]), 2));
  			}else if(imageList.size() == 3){
  				commentImageLayout3.setVisibility(View.VISIBLE);
  				commentImageLayout1.setVisibility(View.GONE);
  				commentImageLayout2.setVisibility(View.GONE);
  				UniversalImageLoadTool.disPlay(imageList.get(0), commentImage31, R.drawable.app_icon_load_image);
  				UniversalImageLoadTool.disPlay(imageList.get(1), commentImage32, R.drawable.app_icon_load_image);
  				UniversalImageLoadTool.disPlay(imageList.get(2), commentImage33, R.drawable.app_icon_load_image);
  				commentImage31.setOnClickListener(imageClickListener((String[])imageList.toArray(new String[imageList.size()]), 1));
  				commentImage32.setOnClickListener(imageClickListener((String[])imageList.toArray(new String[imageList.size()]), 2));
  				commentImage33.setOnClickListener(imageClickListener((String[])imageList.toArray(new String[imageList.size()]), 3));
  			}else{
  				
  			}
  		}else{
  			commentImageLayout.setVisibility(View.GONE);
  		}
  		
  		mDataListView.addHeaderView(mHeadView);
  		
  		//收藏图标
  		if(beanBbsdetail.HasCollect == 0){
  			mCollectImage.setSelected(false);
  		}else if(beanBbsdetail.HasCollect == 1){
  			mCollectImage.setSelected(true);
  		}
  		
  		//点赞图标
  		if(beanBbsdetail.HasFavour == 0){
  			mFavorImage.setSelected(false);
  		}else if(beanBbsdetail.HasFavour == 1){
  			mFavorImage.setSelected(true);
  		}
  		
	}

	 class ViewOnclickListener implements View.OnClickListener{
		 private EditText editText;
		 private boolean isReport;
		 
		 public ViewOnclickListener(){
		 }
		 
		 public ViewOnclickListener(EditText editText){
				this.editText = editText;
		 }
		 
		 public ViewOnclickListener(boolean isReport){
				this.isReport = isReport;
		 }
		 
		 public void onClick(View v) {
			 switch (v.getId()) {
				case R.id.bbs_detail_collect_image: //收藏
					if(LoginUtil.jumpLogin(BbsDetailActivity.this)){
						return;
					}
					if(!mCollectImage.isSelected()){
						requestCollect();
						UmengHelper.CustomEvent(BbsDetailActivity.this, UmengEvent.event_luntan_readitlater);
					}else{
						requestCollectCannel();
					}
					
					break;
				case R.id.bbs_detail_favor_image: //点赞
					if(LoginUtil.jumpLogin(BbsDetailActivity.this)){
						return;
					}
	                if(!mFavorImage.isSelected()){
						requestFavor();
					}else{
						requestFavorCannel();
					}
					break;
				case R.id.bbs_detail_comment_image: //回复，评论
					if(LoginUtil.jumpLogin(BbsDetailActivity.this)){
						return;
					}
					showPopSend("");
					break;
				 case R.id.bbs_detail_share_image: //分享
					 share();
					 UmengHelper.CustomEvent(BbsDetailActivity.this, UmengEvent.event_baike_share);

					 break;
				case R.id.bbs_detail_more_image: //更多
					
					if(!LoginUtil.jumpLogin(BbsDetailActivity.this)){
						showPopSend2();
					}
					break;
				
			    //回复发送
				case R.id.send_text:
					if(TextUtils.isEmpty(editText.getText().toString())){
						UIHelper.showToast(BbsDetailActivity.this, "请输入回复内容");
						return;
					}
					if(editText.getText().toString().length() > 1000){
						UIHelper.showToast(BbsDetailActivity.this, "请输入1000字以内回复内容");
						return;
					}
					requestReply(editText.getText().toString());
					break;
				//取消发送
				case R.id.send_cancel:
					PopUtil.getInstance().dismissPopWindow();
					break;
				case R.id.mother_detail_report: //举报
					if(isReport){
						Intent intent = new Intent(BbsDetailActivity.this, MyReportActivity.class);
						intent.putExtra("reportType", 1);  //1 代表论坛主贴  2代表论坛评论
			            intent.putExtra("reportID", mThreadId);
			            intent.putExtra("reportName", mBeanBbsDetail.Subject);
			            startActivity(intent,true);
					}else{
						Intent intent = new Intent(BbsDetailActivity.this, BbsSendActivity.class);
						Bundle bundle = new Bundle();
						bundle.putSerializable("bbsDetail", mBeanBbsDetail);
			            intent.putExtras(bundle);
			            intent.putExtra("threadId",mThreadId);
			            startActivity(intent,true);
					}
					
		            PopUtil.getInstance().dismissPopWindow();
					break;
				case R.id.mother_detail_cannel: 
					PopUtil.getInstance().dismissPopWindow();
					break;
				default:
					break;
		     }
		 }
	 }

	private void share() {

		if(mBeanBbsDetail == null)
		{
			return;
		}

		String imgPath = SdLocal.getAppIconPath(getApplicationContext());
		String shareUrl = "";

		LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
		if (LoginUtil.checkIsLogin()) {
          	shareUrl = Setting.getShareTopicUrl() + "userID=" + loginInfo.UserID + "&detailID=" + mThreadId;//detailID
		} else {
			shareUrl = Setting.getShareTopicUrl() + "userID=" + "-1" + "&detailID=" + mThreadId;
		}

		List<String> imageList = BeanBbsDetail.parseJsonImage(mBeanBbsDetail.PicUrls);
		if(imageList != null && imageList.size() > 0){
			imgPath = imageList.get(0);
		}

		// 调用官方sdk分享，可以各种形式
		ShareLib.Share(BbsDetailActivity.this, mBeanBbsDetail.Subject, mBeanBbsDetail.Content, imgPath, shareUrl, false, new CallBack() {
			@Override
			public void callBackSuccess(Object obj) {
				super.callBackSuccess(obj);

				//MyNetUtil.getInstance().requestShare(PubContentDetailActivity.this, MyNetUtil.getInstance(), 7, mTopicID);
			}
		});
	}

	//图片监听
	private View.OnClickListener imageClickListener(final String[] urlArray,final int position) {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BbsDetailActivity.this, AppImageBroswerActivity.class);
                intent.putExtra("isShowTopbar", false);
                intent.putExtra("index", position - 1);
                intent.putExtra("urlArray", urlArray);
                startActivity(intent);
            }
        };
    }
	
	//显示回复布局
	@SuppressLint("InflateParams")
	public void showPopSend(String sendToName) {
		View view = LayoutInflater.from(this).inflate(R.layout.bbs_comment_send_view, null);
		TextView sendText = (TextView) view.findViewById(R.id.send_text);
		TextView cancelText = (TextView) view.findViewById(R.id.send_cancel);
		EditText sendContent = (EditText) view.findViewById(R.id.send_edit);
		//sendContent.setFilters(new InputFilter[] { new EmojiFilter() });
		sendContent.setHint("输入您评论的内容");
		sendText.setOnClickListener(new ViewOnclickListener(sendContent));
		cancelText.setOnClickListener(new ViewOnclickListener(sendContent));
		
		PopUtil.getInstance().showPopWindow(this, null, view,Gravity.BOTTOM, null, false);
	}
	
	//举报布局
	@SuppressLint("InflateParams")
	public void showPopSend2() {
		View view = LayoutInflater.from(this).inflate(R.layout.bbs_detail_more_view, null);
		TextView repotText = (TextView) view.findViewById(R.id.mother_detail_report);
		TextView cannelText = (TextView) view.findViewById(R.id.mother_detail_cannel);

		if(mBeanBbsDetail == null){
			return;
		}
		
		if(mBeanBbsDetail.AuthorID.equals(LoginUtil.getUserId())){
			repotText.setText("编辑");
			repotText.setOnClickListener(new ViewOnclickListener(false));
		}else{
			repotText.setText("举报");
			repotText.setOnClickListener(new ViewOnclickListener(true));
		}
		
		cannelText.setOnClickListener(new ViewOnclickListener());
		
		
		PopUtil.getInstance().showPopWindow(this, null, view,Gravity.BOTTOM, null, true);
	}
	
	//请求数据
	public void request(boolean isMore) {

		String request = "";
		int page = 1;
		if (isMore) {
			request = REQUEST_DATA_MORE;
			page = (mCurrentPage + 1);
		} else {
			request = REQUEST_DATA;
			mCurrentPage = page;
		}

		String url = Setting.getBbsDetailUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			
			params.put("ThreadID", mThreadId);
			params.put("PageIndex", page);
			params.put("PageSize", Setting.PAGE_SIZE);
			params.put("RefreshMaxID", mMaxId);
			
		} catch (Exception e) {
			
		}
		map.put("ht", params);
		ApiClient.http_post(url, map, null, this, request, true,false);
	}
	
	//收藏
	public void requestCollect() {
		
		BeanMyArticle beanMyArticle = new BeanMyArticle();
		beanMyArticle.ArticleID = mThreadId;
		beanMyArticle.TargetType = String.valueOf(3);
		beanMyArticle.ArticleTitle = mBeanBbsDetail.Subject;
		if(mBeanBbsDetail.Content != null){
			if(mBeanBbsDetail.Content.length() > 20){
				beanMyArticle.ArticleDescription = mBeanBbsDetail.Content.substring(0, 20);
			}else{
				beanMyArticle.ArticleDescription = mBeanBbsDetail.Content;
			}
		}
		
		MyNetUtil.getInstance().requestAddCollect(this, this,MyNetUtil.REQUEST_ADD_COLLECT, beanMyArticle, 3);
		showProgressDialog();
	}
	
	//取消收藏
	public void requestCollectCannel() {
		MyNetUtil.getInstance().requestCancelCollect(this, this,MyNetUtil.REQUEST_CANCEL_COLLECT, 3, mThreadId);
		showProgressDialog();
	}
	
	//点赞
	public void requestFavor() {
		
		boolean flag = LoginUtil.jumpLogin(this);
		if(flag){
			return;
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			
			params.put("ThreadID", mThreadId);
			params.put("PostID", mBeanBbsDetail.PostID);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(Setting.getBbsFavorUrl(), map, null, this,REQUEST_FAVOR, true,true);
		showProgressDialog();
	}
	
	//取消赞
	public void requestFavorCannel() {
		
		boolean flag = LoginUtil.jumpLogin(this);
		if(flag){
			return;
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			
			params.put("ThreadID", mThreadId);
			params.put("PostID", mBeanBbsDetail.PostID);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(Setting.getBbsFavorCannelUrl(), map, null, this,REQUEST_FAVOR_CANNEL, true,true);
		showProgressDialog();
	}
	
	//回复
	public void requestReply(String sendContent) {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			params.put("ThreadID", mThreadId);
			params.put("PostID", mBeanBbsDetail.PostID);
			params.put("Content", sendContent);
			
		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(Setting.getBbsCommentUrl(), map, null, this,REQUEST_REPLY, true,true);
		showProgressDialog();
	}
	
	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_DATA_SUCCESS:
				
				ArrayList<BeanBbsDetail> dataList = (ArrayList<BeanBbsDetail>) msg.obj;
				
				if (dataList != null && dataList.size() > 0) {
					showHideNoDataLayout(false);
					mBeanBbsDetail = dataList.get(0);
					setInitView(mBeanBbsDetail);
					dataList.remove(0);
					mDataArrayList.clear();
					mDataArrayList.addAll(dataList);
					mDataAdapter = new AdapterBbsDetail(BbsDetailActivity.this,mDataArrayList,mThreadId);
					mDataListView.setAdapter(mDataAdapter);
					
				} else {
					//UIHelper.showToast(BbsDetailActivity.this, R.string.no_data);
                    showHideNoDataLayout(true);
					
					if (mDataArrayList != null && mDataArrayList.size() > 0) {
						mDataArrayList.clear();
					}
				}

				// 更新完后调用该方法结束刷新
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						mGoogleRefreshLayout.setRefreshing(false);  //直接调用是没有用的
					}
				}, 100);

				if (mDataArrayList != null && mDataArrayList.size() > 0) {
					if (mDataArrayList.size() < Setting.PAGE_SIZE) {
						mGoogleRefreshLayout.setLoadMoreFinish(true);
					}
				}else{
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}
				
				break;
			case MSG_DATA_FAIL:
				// 更新完后调用该方法结束刷新
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						mGoogleRefreshLayout.setRefreshing(false);  //直接调用是没有用的
					}
				}, 100);
				showHideNoDataLayout(true);
				break;
			case MSG_DATA_MORE_SUCCESS:

				ArrayList<BeanBbs> dataMoreList = (ArrayList<BeanBbs>) msg.obj;
				
				if (dataMoreList != null && dataMoreList.size() > 0) {
					
				    mDataAdapter.notifyDataSetChanged();

					// 加载更多数据成功，page ++
					mCurrentPage++;
				} else {
					//UIHelper.showToast(BbsDetailActivity.this, R.string.no_data_more);
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			case MSG_DATA_MORE_FAIL:

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;

			//赞
			case MSG_FAVOR_SUCESS:  
				String favorString = (String) msg.obj;
				try {
					JSONObject json = new JSONObject(favorString);
					
					int status = json.getJSONObject("Result").optInt("Status");
					if (status == 200) {
						mFavorImage.setSelected(true);
						mBeanBbsDetail.FavourCount = mBeanBbsDetail.FavourCount+1;
						favorTextView.setText("· 点赞 "+mBeanBbsDetail.FavourCount);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

				hideProgressDialog();
				break;

			case MSG_FAVOR_FAIL:
				hideProgressDialog();
				break;
			case MSG_FAVOR_EXIT_SUCESS:
				String favorCannelString = (String) msg.obj;
				try {
					JSONObject json = new JSONObject(favorCannelString);
					
					int status = json.getJSONObject("Result").optInt("Status");
					if (status == 200) {
						mFavorImage.setSelected(false);
						mBeanBbsDetail.FavourCount = mBeanBbsDetail.FavourCount-1;
						if(mBeanBbsDetail.FavourCount<=0){
							mBeanBbsDetail.FavourCount = 0;
						}
						favorTextView.setText("· 点赞 "+mBeanBbsDetail.FavourCount);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

				hideProgressDialog();
				break;

			case MSG_FAVOR_EXIT_FAIL:
				hideProgressDialog();
				break;
				
			//收藏
			case MSG_COLLECT_SUCESS:  //
				String collectString = (String) msg.obj;
				try {
					JSONObject json = new JSONObject(collectString);
					
					int status = json.getJSONObject("Result").optInt("Status");
					if (status == 200) {
						mCollectImage.setSelected(true);
						UIHelper.showToast(BbsDetailActivity.this, "收藏成功");
						MyTieZiActivity instanceTieZi = (MyTieZiActivity) AppManager.getAppManager().getActivity(MyTieZiActivity.class);
						if (instanceTieZi != null) {
							instanceTieZi.addItem();
						}
						
						mBeanBbsDetail.CollectCount = mBeanBbsDetail.CollectCount+1;
						collectTextView.setText("· 收藏 "+mBeanBbsDetail.CollectCount);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				hideProgressDialog();
				break;

			case MSG_COLLECT_FAIL:
				hideProgressDialog();
				break;
				
			case MSG_COLLECT_CANNEL_SUCESS:
				String collectCannelString = (String) msg.obj;
				try {
					JSONObject json = new JSONObject(collectCannelString);
					
					int status = json.getJSONObject("Result").optInt("Status");
					if (status == 200) {
						mCollectImage.setSelected(false);
						UIHelper.showToast(BbsDetailActivity.this, "取消收藏成功");
						
						MyTieZiActivity instanceTieZi = (MyTieZiActivity) AppManager.getAppManager().getActivity(MyTieZiActivity.class);
						if (instanceTieZi != null) {
							instanceTieZi.removeItem();
						}
						
						mBeanBbsDetail.CollectCount = mBeanBbsDetail.CollectCount-1;
						if(mBeanBbsDetail.CollectCount<=0){
							mBeanBbsDetail.CollectCount = 0;
						}
						collectTextView.setText("· 收藏 "+mBeanBbsDetail.CollectCount);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				hideProgressDialog();
				break;

			case MSG_COLLECT_CANNEL_FAIL:
				hideProgressDialog();
				break;
			case MSG_REPLY_SUCESS:
				String replyString = (String) msg.obj;
				try {
					JSONObject json = new JSONObject(replyString);
					
					int status = json.getJSONObject("Result").optInt("Status");
					if (status == 200) {
						PopUtil.getInstance().dismissPopWindow();
						//刷新
						request(false);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

				hideProgressDialog();
				break;
			case MSG_REPLY_FAIL:
				break;
			default:
				break;
			}
		};
	};
	
	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			ArrayList<BeanBbsDetail> dataArraylist = BeanBbsDetail.parseJsonData((String) data);

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = dataArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			ArrayList<BeanBbsDetail> dataMoreArraylist = BeanBbsDetail.parseJsonData((String) data);

			if (dataMoreArraylist != null && dataMoreArraylist.size() > 0) {
				mDataArrayList.addAll(dataMoreArraylist);
			}

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_MORE_SUCCESS;
			msg.obj = dataMoreArraylist;
			mHandler.sendMessage(msg);
		}else if(object.equals(REQUEST_FAVOR)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_FAVOR_SUCESS;
			msg.obj = (String) data;
			mHandler.sendMessage(msg);
		}else if(object.equals(REQUEST_FAVOR_CANNEL)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_FAVOR_EXIT_SUCESS;
			msg.obj = (String) data;
			mHandler.sendMessage(msg);
		}else if(object.equals(MyNetUtil.REQUEST_ADD_COLLECT)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_COLLECT_SUCESS;
			msg.obj = (String) data;
			mHandler.sendMessage(msg);
		}else if(object.equals(MyNetUtil.REQUEST_CANCEL_COLLECT)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_COLLECT_CANNEL_SUCESS;
			msg.obj = (String) data;
			mHandler.sendMessage(msg);
		}else if(object.equals(REQUEST_REPLY)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_REPLY_SUCESS;
			msg.obj = (String) data;
			mHandler.sendMessage(msg);
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_DATA)) {
			mHandler.sendEmptyMessage(MSG_DATA_FAIL);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			mHandler.sendEmptyMessage(MSG_DATA_MORE_FAIL);
		} else if(object.equals(REQUEST_FAVOR)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_FAVOR_FAIL;
			mHandler.sendMessage(msg);
		}else if(object.equals(REQUEST_FAVOR_CANNEL)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_FAVOR_EXIT_FAIL;
			mHandler.sendMessage(msg);
		}else if(object.equals(MyNetUtil.REQUEST_ADD_COLLECT)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_COLLECT_FAIL;
			mHandler.sendMessage(msg);
		}else if(object.equals(MyNetUtil.REQUEST_CANCEL_COLLECT)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_COLLECT_CANNEL_FAIL;
			mHandler.sendMessage(msg);
		}else if(object.equals(REQUEST_REPLY)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_REPLY_FAIL;
			mHandler.sendMessage(msg);
		}
	}

	@Override
	public void onLoad() {
		request(true);
	}

	@Override
	public void onRefresh() {
		request(false);
	}
}
